import { NextRequest, NextResponse } from "next/server";
import { getCurrentUserId } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { createEmbeddings } from "@/lib/embeddings";
import { parseDocument } from "@/lib/document-parser";
import { PrismaClient, Prisma } from "@prisma/client";

// 文件上传大小限制 (50MB)
const MAX_FILE_SIZE = 50 * 1024 * 1024;

export async function POST(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const userId = getCurrentUserId();

    // 验证用户认证
    if (!userId) {
      return NextResponse.json(
        { success: false, error: "未授权" },
        { status: 401 }
      );
    }

    // 获取知识库ID
    const knowledgeBaseId = params.id;

    // 验证知识库是否存在且属于当前用户
    const user = await prisma.user.findUnique({
      where: { clerkId: userId },
    });

    if (!user) {
      return NextResponse.json(
        { success: false, error: "用户不存在" },
        { status: 404 }
      );
    }

    const knowledgeBase = await prisma.knowledgeBase.findFirst({
      where: {
        id: knowledgeBaseId,
        userId: user.id,
      },
    });

    if (!knowledgeBase) {
      return NextResponse.json(
        { success: false, error: "知识库不存在或无权访问" },
        { status: 404 }
      );
    }

    // 处理文件上传
    const formData = await req.formData();
    const file = formData.get("file") as File | null;

    if (!file) {
      return NextResponse.json(
        { success: false, error: "未找到文件" },
        { status: 400 }
      );
    }

    // 检查文件大小
    if (file.size > MAX_FILE_SIZE) {
      return NextResponse.json(
        { success: false, error: "文件大小超出限制（最大50MB）" },
        { status: 400 }
      );
    }

    // 检查文件类型
    const allowedTypes = [
      "application/pdf",
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "text/plain",
      "text/markdown",
    ];

    const fileType = file.type;
    const fileName = file.name;
    const fileExtension = fileName.split(".").pop()?.toLowerCase();

    // 检查文件类型是否允许
    if (
      !allowedTypes.includes(fileType) &&
      !["pdf", "docx", "txt", "md"].includes(fileExtension || "")
    ) {
      return NextResponse.json(
        { success: false, error: "不支持的文件类型" },
        { status: 400 }
      );
    }

    // 解析文件内容
    const fileContent = await file.arrayBuffer();
    
    // 解析文档内容
    const { content, chunks } = await parseDocument(fileContent, fileName);

    if (!content || !chunks || chunks.length === 0) {
      return NextResponse.json(
        { success: false, error: "无法解析文件内容" },
        { status: 400 }
      );
    }

    // 数据库事务：创建文档和向量
    const document = await prisma.$transaction(async (tx: Prisma.TransactionClient) => {
      // 创建文档记录
      const doc = await tx.document.create({
        data: {
          name: fileName,
          content: content,
          fileType: fileType || `application/${fileExtension}`,
          fileSize: file.size,
          knowledgeBaseId: knowledgeBaseId,
        },
      });

      // 对每个文本块创建嵌入向量
      for (const chunk of chunks) {
        try {
          // 生成嵌入向量
          const embedding = await createEmbeddings(chunk);
          
          if (embedding && embedding.length > 0) {
            // 创建向量记录
            await tx.vector.create({
              data: {
                content: chunk,
                embedding: embedding,
                documentId: doc.id,
              },
            });
          }
        } catch (embeddingError) {
          console.error("创建嵌入向量失败:", embeddingError);
          // 继续处理下一个块，不中断整个过程
        }
      }

      return doc;
    });

    // 返回成功响应
    return NextResponse.json({
      success: true,
      data: {
        id: document.id,
        name: document.name,
        fileType: document.fileType,
        fileSize: document.fileSize,
      },
    });
  } catch (error) {
    console.error("文件上传处理错误:", error);
    return NextResponse.json(
      { success: false, error: "处理文件时出错" },
      { status: 500 }
    );
  }
} 